package com.tang.log.async;

import com.tang.framework.async.AbstractAsyncHandler;
import com.tang.framework.async.model.AsyncLog;
import com.tang.framework.log.enums.LogType;
import com.tang.log.domain.AdminErrorLog;
import com.tang.log.domain.AdminSuccessLog;
import com.tang.log.domain.AppErrorLog;
import com.tang.log.domain.AppSuccessLog;
import com.tang.log.repository.AdminErrorLogRepository;
import com.tang.log.repository.AdminSuccessLogRepository;
import com.tang.log.repository.AppErrorLogRepository;
import com.tang.log.repository.AppSuccessLogRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * @Author tang jun liang
 * @Date 2023/5/20 17:24
 */
@Service(value = "asyncLog")
public class RequestAsyncLogHandler extends AbstractAsyncHandler<AsyncLog> {

    @Resource
    private AdminErrorLogRepository adminErrorLogRepository;

    @Resource
    private AdminSuccessLogRepository adminSuccessLogRepository;

    @Resource
    private AppSuccessLogRepository appSuccessLogRepository;


    @Resource
    private AppErrorLogRepository appErrorLogRepository;


    @Override
    protected void async0(AsyncLog asyncLog) {
        if (asyncLog.getError()) {
            if (asyncLog.getLogType().equals(LogType.ADMIN)) {
                processAdminErrorLog(asyncLog);
            } else {
                processAppErrorLog(asyncLog);
            }
        } else {
            if (asyncLog.getLogType().equals(LogType.ADMIN)) {
                processAdminSuccessLog(asyncLog);
            } else {
                processAppSuccessLog(asyncLog);
            }
        }
    }


    private void processAdminSuccessLog(AsyncLog asyncLog) {
        AdminSuccessLog adminSuccessLog = new AdminSuccessLog();
        BeanUtils.copyProperties(asyncLog, adminSuccessLog);
        adminSuccessLogRepository.save(adminSuccessLog);
    }

    private void processAdminErrorLog(AsyncLog asyncLog) {
        AdminErrorLog adminErrorLog = new AdminErrorLog();
        BeanUtils.copyProperties(asyncLog, adminErrorLog);
        adminErrorLogRepository.save(adminErrorLog);
    }

    private void processAppSuccessLog(AsyncLog asyncLog) {
        AppSuccessLog appSuccessLog = new AppSuccessLog();
        BeanUtils.copyProperties(asyncLog, appSuccessLog);
        appSuccessLogRepository.save(appSuccessLog);
    }

    private void processAppErrorLog(AsyncLog asyncLog) {
        AppErrorLog appErrorLog = new AppErrorLog();
        BeanUtils.copyProperties(asyncLog, appErrorLog);
        appErrorLogRepository.save(appErrorLog);
    }
}
